import os
from pathlib import Path
import shutil
import time
from datetime import datetime, timedelta

import schedule

LOG_FILE = "pyDoubleDayCleaner.log"
SAVE_FOLDER = "E:\\Game\\Steamcmd\\steamapps\\common\\PalServer\\Pal"
TIMER = "04:05:00"  # 每天04:05执行一次


def cleaner():
    pass


def remove_files() -> None:
    target_date: datetime = datetime.now() - timedelta(days=7)
    if target_date.day % 2 == 0:
        # 双数天删除
        target_saved: str = "Saved-" + target_date.strftime("%y%m%d") + "_040000"
        save_data = os.path.join(SAVE_FOLDER, target_saved)
        if os.path.exists(save_data):
            shutil.rmtree(save_data)
            mylog(f"已删除文件夹{target_date}")
        else:
            mylog(f"{save_data}不存在")
        return
    else:
        # 单数天不删除
        return


def mylog(s: str = ""):
    s = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]" + s
    print(s)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(s + "\n")
        f.close()


if __name__ == "__main__":
    os.system("title pyDoubleDayCleaner")
    if not os.path.exists(LOG_FILE):
        Path(LOG_FILE).touch()
    schedule.run_pending()
    schedule.every().day.at(TIMER).do(remove_files)
    mylog(f"[Init] Program will clean {SAVE_FOLDER} at {TIMER} everyday")
    while True:
        schedule.run_pending()
        time.sleep(10)
